import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:yyshort/common/apis/apis.dart';
import 'package:yyshort/common/utils/json_storage_util.dart';
import 'package:yyshort/common/utils/utils.dart';
import 'package:yyshort/pages/ali_player/short_video/SharedDataController.dart';
import 'package:yyshort/pages/home/controller.dart';
import 'package:yyshort/pages/payment/index.dart';
import '../../common/store/config.dart';

class LanguageSelectionPage extends StatelessWidget {
  final ConfigStore _configStore = ConfigStore.to;

  final List<Map<String, dynamic>> _languageOptions = [
    {'locale': Locale('en'), 'name': 'English', 'description': '英文'},
    {'locale': Locale('es'), 'name': 'Spanish', 'description': '西班牙文'},
    // {'locale': Locale('zh', 'Hans'), 'name': '简体中文', 'description': '简体中文'},
    {'locale': Locale('hant'), 'name': '繁体中文', 'description': '繁体中文'},
    {'locale': Locale('ja'), 'name': '日本語', 'description': '日文'},
  ];

  LanguageSelectionPage({super.key}) {}

  @override
  Widget build(BuildContext context) {
    Get.lazyPut(() => PaymentController());

    return Scaffold(
      backgroundColor: Colors.black,
      appBar: AppBar(
        backgroundColor: Colors.black,
        title: Text('语言设置'.tr, style: TextStyle(color: Colors.white)),
        iconTheme: IconThemeData(color: Colors.white),
        elevation: 0,
      ),
      body: ListView.separated(
        padding: EdgeInsets.symmetric(vertical: 16),
        itemCount: _languageOptions.length,
        separatorBuilder: (context, index) => Divider(
          color: Colors.white24,
          height: 1,
          indent: 16,
          endIndent: 16,
        ),
        itemBuilder: (context, index) {
          final option = _languageOptions[index];
          return Obx(() {
            // 正确访问可观察变量的值（通过 .value）
            final isSelected =
                _configStore.locale?.languageCode ==
                option['locale'].languageCode;
            //     &&
            // _configStore.locale?.countryCode ==
            //     option['locale'].countryCode;

            return ListTile(
              contentPadding: EdgeInsets.symmetric(horizontal: 16),
              // leading: Icon(
              //   isSelected ? Icons.check_circle : Icons.circle_outlined,
              //   color: Colors.white,
              // ),
              title: Text(
                option['name'],
                style: TextStyle(color: Colors.white, fontSize: 16),
              ),
              subtitle: Text(
                (option['description'] as String).tr,
                style: TextStyle(color: Colors.white70, fontSize: 14),
              ),
              trailing: isSelected
                  ? Icon(Icons.check_circle, color: Colors.white)
                  : null,
              onTap: () async {
                Locale locale = option['locale'];
                _configStore.onLocaleUpdate(locale);
                Get.forceAppUpdate();

                bool result;
                // if (ConfigStore.to.locale!.languageCode == 'zh') {
                //   result = await UserAPI.set_user_language(language: 'hant');
                // } else {
                result = await UserAPI.set_user_language(
                  language: locale.languageCode,
                );
                // }
                if (result) {
                  // EasyLoading.showSuccess('');

                  //获取首页更新
                  final temPonnalCTL = Get.find<HomeController>();
                  temPonnalCTL.onReady();
                  //支付列表刷新
                  final paymentCTL = Get.find<PaymentController>();
                  paymentCTL.fetchRechargeList();

                  //for_you页面刷新；
                  await JsonStorageUtil.deleteJson(key: 'for_you_videos');

                  eventBus.fire(LanguageChangeRefreshEvent());
                }
              },
            );
          });
        },
      ),
    );
  }
}
